const app = getApp();
import api from './api.js';
import storage from './Storge.js';
import { tokenKey } from './constant.js';
import net from './Request.js';


//重定向到Login,从TAB跳转过来
const redirectToLogin = (sourceRoute) => {
    var url = '../login/login';
    if (sourceRoute != null) {
        url += '?src=' + sourceRoute;
    }
    console.log(url);
    wx.redirectTo({
        url: url,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
    });
}
// 登录成功后,跳转回去TAB
const redirectToTab = (route) => {
    var url = '../order/order'; //default page
    if (route != null) {
        url = '../../' + route;
    }

    console.log('redirectToTab == ', route);
    wx.switchTab({
        url: url,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
    });
}

//Token 过期,用refredsh_token 刷新Token
const refreshToken = (route) => {
    console.log('refreshToken start route', route);
    storage.getCache(tokenKey).then(res => {
        return res.data;
    }).catch(e => {
        console.error('token not found!!! 重定向到Login页面', e);
        redirectToLogin(route);
        return Promise.reject({
            notRealPromiseException: 'token not found!!! 重定向到Login页面'
        });
    }).then(res => {
        wx.showNavigationBarLoading();
        net.post(api.baseUrl + 'oauth/token', {
            'grant_type': api.refresh_token_grant_type,
            'refresh_token': res.refresh_token,
            'client_id': api.client_id,
            'client_secret': api.client_secret
        }).then(res => {
            console.log("reget refreshToken ", res);
            app.globalData.access_token = res.data;
            storage.setCache(tokenKey, res.data).then(res => {
                redirectToTab(route);
            });
        }).catch(e => {
            storage.removeCache(tokenKey);
            redirectToLogin(route);
            console.error('重新获取refreshToken失败,重定向到Login页面', e);
        }).then(() => {
            wx.hideNavigationBarLoading();
        })
    });
}

// 检查 token 是否存在,不保存还可用
const checkTokenExits = (route) => {
    console.log('检查 token 是否存在,不保存还可用 ', route);
    return new Promise((resolve, reject) => {
        storage.getCache(tokenKey).then(res => {
            return res.data.access_token;
        }).then(res => {
            resolve(res);
        }).catch(e => {
            console.error('checkTokenExits() onLoad ', e);
            reject();
            refreshToken(route);
        });
    });
}

//上传图片
const uploadImage = accessToken => {
    new Promise((resolve, reject) => {
        wx.chooseImage({
            count: 1,
            sizeType: 'compressed',
            success: res => resolve(res),
            fail: reject
        });
    }).then(res => {
        console.log(res);
        var tempFilePaths = res.tempFilePaths;
        return tempFilePaths[0];
    }).catch(e => {
        console.error('choose image error ', e);
        return Promise.reject({
            exception: e
        });
    }).then(res => {
        console.log(res);
        console.log('choose image', res);

        net.upload(api.baseUrl + 'api/uploadImage', res, 'file', {
            'access_token': accessToken
        }).then(res => res.data).then(res => {

            console.log('success upload', res);
        }).catch(e => {
            console.error('uplaod failed ...', e);
        });

    });
}

//检查Token是否存在,过期重新获取,没有重定向到Login页面
const checkAndFetchToken = (route, fetchDataFunction, data) => {
    return new Promise((resolve, reject) => {
        checkTokenExits(route).then(res => {
            var tokenData = {
                'access_token': res
            }
            app.globalData.access_token = tokenData;
            if (typeof fetchDataFunction === 'function') {
                resolve(fetchDataFunction(data, tokenData));
            } else {
                reject({
                    cause: 'param not a function'
                });
            }
        }).catch(e => {
            console.error("order message ", e)
            reject({
                cause: e
            })
        });
    });
}

export {
    redirectToLogin,
    refreshToken,
    redirectToTab,
    checkTokenExits,
    uploadImage,
    checkAndFetchToken
}